package dao;

import java.util.Iterator;
import java.util.List;

import model.User;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UserDAO {

	@SuppressWarnings("rawtypes")
	public User findByID(long id) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		String SQL_QUERY = "from user user";
		Query query = session.createQuery(SQL_QUERY);
		for (Iterator it = query.iterate(); it.hasNext();) {
			User user = (User) it.next();
			if (user.getIdUser() == id) {
				session.close();
				sessionFactory.close();
				return user;
			}
		}
		session.close();
		sessionFactory.close();
		return null;
	}

	public void addUser(User user) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(user);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	public void updateUser(User user) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.update(user);

		Transaction transaction = session.beginTransaction();
		session.update(user);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	public void deleteUser(User user) {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.delete(user);
		transaction.commit();
		session.flush();
		session.close();
		sessionFactory.close();
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll() {
		SessionFactory sessionFactory = new Configuration().configure(
				"/app/hibernate.cfg.xml").buildSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.class);
		List<User> user = criteria.list();
		session.close();
		sessionFactory.close();
		return user;
	}
}
